<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 用户列表 -->
      <el-col :span="6">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>客户列表</span>
            <el-input
              placeholder="搜索客户"
              v-model="searchKeyword"
              clearable
              prefix-icon="el-icon-search"
              size="small"
              style="margin-top: 10px;"
            ></el-input>
          </div>
          <div class="user-list">
            <div 
              v-for="user in filteredUsers" 
              :key="user.userId" 
              class="user-item" 
              :class="{ 'active': currentUser && currentUser.userId === user.userId }"
              @click="selectUser(user)"
            >
              <el-badge :value="user.unreadCount > 0 ? user.unreadCount : ''" class="user-badge">
                <el-avatar :size="40" icon="el-icon-user-solid"></el-avatar>
              </el-badge>
              <div class="user-info">
                <div class="user-name">{{ user.nickname }}</div>
                <div class="user-message">{{ user.lastMessage || '暂无消息' }}</div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <!-- 聊天区域 -->
      <el-col :span="18">
        <el-card class="box-card">
          <div slot="header" class="clearfix" v-if="currentUser">
            <span>{{ currentUser.nickname }}</span>
          </div>
          <div v-if="!currentUser" class="chat-placeholder">
            <i class="el-icon-chat-line-round" style="font-size: 50px;"></i>
            <p>请选择一个客户开始聊天</p>
          </div>
          <div v-else class="chat-container">
            <!-- 消息列表 -->
            <div class="message-list">
              <div 
                v-for="(msg, index) in messages" 
                :key="index" 
                class="message-item"
                :class="{'message-right': msg.fromUserId === serviceId}"
              >
                <div class="message-content">{{ msg.content }}</div>
                <div class="message-time">{{ formatTime(msg.createTime) }}</div>
              </div>
            </div>
            
            <!-- 输入框 -->
            <div class="input-area">
              <el-input
                type="textarea"
                :rows="3"
                placeholder="请输入消息内容..."
                v-model="inputMessage"
              ></el-input>
              <div class="btn-area">
                <el-button type="primary" @click="sendMessage">发送</el-button>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getChatUserList, getChatHistory, sendChatMessage, markAsRead } from "@/api/company/chat";

export default {
  name: "CustomerChat",
  data() {
    return {
      // 客服ID (模拟)
      serviceId: "1",
      // 客户列表
      userList: [
        { userId: "APP_USER_1", nickname: "张先生", lastMessage: "您好，请问有什么可以帮到您的？", unreadCount: 2 },
        { userId: "APP_USER_2", nickname: "李女士", lastMessage: "我想预约一个保洁服务", unreadCount: 0 },
        { userId: "APP_USER_3", nickname: "王先生", lastMessage: "您好，我的订单什么时候能安排服务人员上门？", unreadCount: 1 }
      ],
      // 搜索关键词
      searchKeyword: "",
      // 当前选中的用户
      currentUser: null,
      // 聊天消息
      messages: [],
      // 输入框消息
      inputMessage: ""
    };
  },
  computed: {
    filteredUsers() {
      if (!this.searchKeyword) {
        return this.userList;
      }
      return this.userList.filter(user => 
        user.nickname && user.nickname.toLowerCase().includes(this.searchKeyword.toLowerCase())
      );
    }
  },
  methods: {
    // 选择用户
    selectUser(user) {
      this.currentUser = user;
      // 模拟加载聊天记录
      this.messages = [
        { id: 1, fromUserId: "APP_USER_1", toUserId: "1", content: "您好，请问有什么可以帮到您的？", messageType: "0", createTime: new Date(new Date().getTime() - 3600000) },
        { id: 2, fromUserId: "1", toUserId: "APP_USER_1", content: "您好，我们有各种家政服务，请问您需要什么服务？", messageType: "0", createTime: new Date(new Date().getTime() - 3500000) },
        { id: 3, fromUserId: "APP_USER_1", toUserId: "1", content: "我需要一个日常保洁服务", messageType: "0", createTime: new Date(new Date().getTime() - 3400000) }
      ];
      
      // 实际项目中应该调用API
      /*
      getChatHistory(user.userId, this.serviceId).then(response => {
        this.messages = response.data;
        // 标记为已读
        if (user.unreadCount > 0) {
          markAsRead(user.userId, this.serviceId);
          // 更新未读数
          user.unreadCount = 0;
        }
      });
      */
    },
    // 发送消息
    sendMessage() {
      if (!this.currentUser || !this.inputMessage.trim()) return;
      
      // 添加到本地消息列表
      const message = {
        id: this.messages.length + 1,
        fromUserId: this.serviceId,
        toUserId: this.currentUser.userId,
        content: this.inputMessage,
        messageType: "0",
        createTime: new Date()
      };
      
      this.messages.push(message);
      this.inputMessage = "";
      
      // 实际项目中应该调用API
      /*
      sendChatMessage({
        toUserId: this.currentUser.userId,
        content: message.content,
        messageType: "0"
      });
      */
    },
    // 格式化时间
    formatTime(time) {
      if (!time) return '';
      
      const date = new Date(time);
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      
      return `${hours}:${minutes}`;
    }
  }
};
</script>

<style scoped>
.box-card {
  height: 600px;
  display: flex;
  flex-direction: column;
}

.user-list {
  overflow-y: auto;
  max-height: 520px;
}

.user-item {
  display: flex;
  padding: 10px;
  cursor: pointer;
  border-bottom: 1px solid #f0f0f0;
}

.user-item:hover {
  background-color: #f5f7fa;
}

.user-item.active {
  background-color: #ecf5ff;
}

.user-badge {
  margin-right: 10px;
}

.user-info {
  flex: 1;
}

.user-name {
  font-weight: bold;
  margin-bottom: 5px;
}

.user-message {
  color: #999;
  font-size: 13px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.chat-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 500px;
  color: #909399;
}

.chat-container {
  display: flex;
  flex-direction: column;
  height: 520px;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.message-item {
  margin-bottom: 15px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.message-right {
  align-items: flex-end;
}

.message-content {
  max-width: 70%;
  padding: 10px;
  border-radius: 4px;
  background-color: #f2f6fc;
  word-break: break-word;
}

.message-right .message-content {
  background-color: #e1f3ff;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.input-area {
  padding: 10px;
  border-top: 1px solid #ebeef5;
}

.btn-area {
  margin-top: 10px;
  text-align: right;
}
</style> 